package com.zznode.client.wlanpolling.test;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;

import android.widget.Toast;

import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.model.SystemSetting;
import com.zznode.client.wlanpolling.model.TestResultConstants;
import com.zznode.client.wlanpolling.model.WLANPollManager;
import com.zznode.client.wlanpolling.utils.PingUtils;



public class FTPUploadActivity extends FTPRateChartActivity {

	@Override
	protected String getLabel() {
		return "FTP上传测试";
	}

	@Override
	protected boolean isValidForTesting() {
		SystemSetting setting = ((WLANPollingApplication)getApplication()).getContext().getSystemSetting();
		String url = setting.getUploadFileUrl();
		if(url == null || "".equals(url)){
			Toast.makeText(getBaseContext(), "请先在功能设置界面“FTP上传测试文件路径设置”后再进行此测试", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}
	
	private String replaceStr(String str1, String str2) {
		return str1.replace(str2, "");
	}
	
	@Override
	protected void doSave() {
		String apMac = PingUtils.clearMacAdress(application.getContext().getCurrentWifi().getBSSID());

		Map<String, Object> values = new HashMap<String, Object>();
		
		values.put(TestResultConstants.UPLOADDATASIZE, replaceStr(tv_allsize.getText().toString(), "KB"));
		values.put(TestResultConstants.UPLOADSPEED, replaceStr(tv_avgSpeed.getText().toString(), "KB/s"));
		values.put(TestResultConstants.SSID, application.getContext().getCurrentWifi().getSSID());
		
		WLANPollManager.getWLANPollManager().updateTestResult(application.getApplicationContext(), 
				apMac,
				values);
		Toast.makeText(this, "成功保存", Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void doFTPOperation(FTPClient client) throws Exception {
		int totalSize = 0;
//		long totalTime = 0;
			long currentTime = 0, lastTime = 0, lastSize = 0;
			long beginTime = 0;
			int count = 0;
		String[] dirs = dir.split("/");
		if(dirs != null && dirs.length > 0){
			for(int i = 0; i < dirs.length; i++){
				client.changeWorkingDirectory(dirs[i]);
			}
		}
		SystemSetting setting = ((WLANPollingApplication)getApplication()).getContext().getSystemSetting();
		String url = setting.getUploadFileUrl();
		if(url == null || "".equals(url)){
			uiRun(new Runnable(){
				public void run(){
					Toast.makeText(getBaseContext(), "请先设置上传文件路径再进行此测试", Toast.LENGTH_LONG).show();
				}
			});
			return;
		}
		File uploadFile = new File(url);
		allSize = uploadFile.length();
		InputStream is = new FileInputStream(uploadFile);
		if(fileName == null){
			fileName = "temp.tmp";
		}
		String uplaodFilename = uploadFile.getName();
		OutputStream os = client.storeFileStream(uplaodFilename);
		
		BufferedOutputStream bos = new BufferedOutputStream(os, client.getBufferSize());
		byte[] buffer = new byte[client.getBufferSize()];
		beginTime = System.currentTimeMillis();
		int avgSpeed;
		int val;
		while (!stopped && (val = is.read(buffer)) != -1) {
			totalSize += val;
			bos.write(buffer, 0, val);
			long systemTime = System.currentTimeMillis();
			if(systemTime - currentTime > 1000) {
				count++;
				lastTime = currentTime;
				currentTime = systemTime;
//			totalTime = currentTime - beginTime;
				int speed = (int)((totalSize - lastSize) /((systemTime - lastTime)/1000));
				if (systemTime - beginTime > 1000) {
					avgSpeed = (int)(totalSize / ((systemTime - beginTime) / 1000));
					currentSpeed = speed/1024;
					averageSpeed = avgSpeed/1024;
					updateSpeed();
				}
				category.clear();
				double realValue = (double)speed / (double)1024;
				category.add("", dashboardValue(realValue));
				dataset.getSeriesAt(0).add(count, speed/1024.0);
				lastSize = totalSize;
				updateChart();
				completedSize = totalSize;
				updateSummary();
			}
		}
		is.close();
		os.close();
		completedSize = totalSize;
	}

}
